package com.house.twohouse.config;

import com.alibaba.fastjson.JSON;
import com.house.twohouse.dao.FlatsDao;
import com.house.twohouse.entity.vo.FlatsVo;
import com.house.twohouse.service.FlatsService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassNameMyRun
 * @Description TODO
 * @Author
 * @DATE2022/4/26 8:24
 */
@Component
@SuppressWarnings("all")
public class MyRun implements ApplicationRunner {
    @Autowired
    private FlatsService flatsService;
    @Autowired
    private RestHighLevelClient client;
    //项目启动同步数据进es
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<FlatsVo> list = flatsService.getlist();
        BulkRequest bulkRequest= new BulkRequest();
        for (FlatsVo flatsVo : list) {
            IndexRequest request = new IndexRequest("house");
            request.id(flatsVo.getFlatsId().toString());
            String jsonString = JSON.toJSONString(flatsVo);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
    }
    //同步es
    @Scheduled(cron ="0/2 * * * * ?")
    public void asyn() throws Exception {
        System.out.println("两秒同步一次es");
        run(null);
    }
}
